package com.demo.drools.controller;


import cn.hutool.core.util.StrUtil;


import com.alibaba.fastjson.JSONObject;
import com.demo.drools.bean.QmsRule;
import com.demo.drools.bean.RoleDict;
import com.demo.drools.service.QmsRuleService;
import com.demo.drools.service.RulesService;
import org.drools.compiler.lang.DrlDumper;
import org.drools.compiler.lang.api.*;
import org.drools.compiler.lang.descr.AndDescr;
import org.drools.compiler.lang.descr.PackageDescr;
import org.drools.core.impl.InternalKnowledgeBase;
import org.drools.core.impl.KnowledgeBaseFactory;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieSession;
import org.kie.internal.builder.KnowledgeBuilder;
import org.kie.internal.builder.KnowledgeBuilderError;
import org.kie.internal.builder.KnowledgeBuilderErrors;
import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.kie.internal.io.ResourceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.smartcardio.Card;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;


@Controller
@RequestMapping(value = "/rules")
public class RulesController {

    @Autowired
    private RulesService rulesService;
    @Resource
    private QmsRuleService qmsRuleService;

    @RequestMapping(value ="/write/{id}" ,method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public ResponseEntity<Object> getRuleByWrite(@PathVariable Integer id) {

        return new ResponseEntity<>(rulesService.executeRules(id), HttpStatus.OK);
    }

    @RequestMapping(value ="/write/getList/{ruleCode}" ,method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public ResponseEntity<Object> getList(@PathVariable("ruleCode") String ruleCode){
        String param = "param";
        String drools = "drools";

        int int1 = 1;
        int int2 = 1;
        int int3 = 5;
        String drlString = getDrlRules();
        KnowledgeBuilder kb = KnowledgeBuilderFactory.newKnowledgeBuilder();
        kb.add(ResourceFactory.newByteArrayResource(drlString.getBytes(StandardCharsets.UTF_8)), ResourceType.DRL);
        KnowledgeBuilderErrors errors = kb.getErrors();
        for (KnowledgeBuilderError error : errors) {
            System.out.println("规则文件正确性有误：" + error);
        }
        InternalKnowledgeBase kBase =  KnowledgeBaseFactory.newKnowledgeBase();
       // kBase.addKnowledgePackages(kb.getKnowledgePackages());
        kBase.addPackages(kb.getKnowledgePackages());
        KieSession kieSession1 = kBase.newKieSession();
        RoleDict roleDict = new RoleDict();
        roleDict.setScheduling_cycle(int1);
        roleDict.setReport_term_of_validity(int2);
        roleDict.setEarly_warning_period(int3);
        roleDict.setCode(ruleCode);
        HashMap<String, Boolean> paramValue = new HashMap<>();
        paramValue.put("result", false);
        kieSession1.setGlobal(param, paramValue);
        kieSession1.insert(roleDict);
        kieSession1.fireAllRules();
        kieSession1.dispose();
        //System.out.println(paramValue.get("result"));
        return new ResponseEntity<>(paramValue.get("result"),HttpStatus.OK);
    }

    String getDrlRules() {
        PackageDescrBuilder pkgDescBuilder = DescrFactory.newPackage().name("drools")
                .newImport()
                .target(RoleDict.class.getName())
                .end()
                .name("drools")
                .newGlobal()
                .identifier("param")
                .type(HashMap.class.getName())
                .end();

        List<QmsRule> rules = qmsRuleService.list();
        for (QmsRule rule : rules) {
            RuleDescrBuilder ruleDescrBuilder = pkgDescBuilder.newRule().name(rule.getRuleCode());
            //attribute
            ruleDescrBuilder.attribute("salience", "0");

            //lhs
            PatternDescrBuilder<CEDescrBuilder<RuleDescrBuilder, AndDescr>> pattern = ruleDescrBuilder.lhs().pattern(Card.class.getSimpleName());
            List<String> ruleCondition = JSONObject.parseArray(rule.getRuleCondition()).toJavaList(String.class);
            for (String constraint : ruleCondition) {
                if (!StrUtil.isEmpty(constraint)) {
                    pattern.constraint(constraint);
                }
            }
            pattern.type(RoleDict.class.getName());
            pattern.end();

            //rhs
            ruleDescrBuilder.rhs("param" + ".put(\"result\",true);");
            ruleDescrBuilder.end();
        }
        pkgDescBuilder.end();

        //dump to String;
        PackageDescr packageDescr = pkgDescBuilder.getDescr();
        DrlDumper dumper = new DrlDumper();
        String drl = dumper.dump(packageDescr);
        System.out.println(drl);
        return drl;
    }



}
